<?php

/**
 * This is the model class for table "horarios".
 *
 * The followings are the available columns in table 'horarios':
 * @property integer $id_horario
 * @property integer $id_curso
 * @property integer $id_aula
 * @property string $dia_semana
 * @property string $hora_inicio
 * @property string $hora_fin
 *
 * The followings are the available model relations:
 * @property Aulas $idAula
 * @property Cursos $idCurso
 * @property Clases[] $clases
 * @property Solicitudescambiohorario[] $solicitudescambiohorarios
 */
class Horarios extends CActiveRecord
{
	private $old = array();

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'horarios';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('id_aula, dia_semana, hora_inicio, hora_fin', 'required'),
			array('id_curso, id_aula', 'numerical', 'integerOnly'=>true),
			array('dia_semana', 'length', 'max'=>100),
			array('hora_inicio, hora_fin', 'date','format'=>'HH:mm:ss','message'=>'Error al cargar {attribute} - El formato requerido es  HH:mm:ss'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id_horario, id_curso, id_aula, dia_semana, hora_inicio, hora_fin', 'safe', 'on'=>'search'),
			array('hora_fin', 'compare', 'compareAttribute'=>'hora_inicio','operator'=>'>'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'idAula' => array(self::BELONGS_TO, 'Aulas', 'id_aula'),
			'idCurso' => array(self::BELONGS_TO, 'Cursos', 'id_curso'),
			'clases' => array(self::HAS_MANY, 'Clases', 'id_horario'),
			'solicitudescambiohorarios' => array(self::MANY_MANY, 'Solicitudescambiohorario', 'horarios_solicitudescambio(id_horario, id_solicitud)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id_horario' => 'Horario',
			'id_curso' => 'Curso',
			'id_aula' => 'Aula',
			'dia_semana' => 'Día de la semana',
			'hora_inicio' => 'Hora de inicio',
			'hora_fin' => 'Hora de fin',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id_horario',$this->id_horario);
		$criteria->compare('id_curso',$this->id_curso);
		$criteria->compare('id_aula',$this->id_aula);
		$criteria->compare('dia_semana',$this->dia_semana,true);
		$criteria->compare('hora_inicio',$this->hora_inicio,true);
		$criteria->compare('hora_fin',$this->hora_fin,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Horarios the static model class
	 */

	function getDisplay() // Función en que concatena la fecha inicial y final del periodo lectivo
	{
	    return $this->dia_semana.': '.
	    	date('H:i',strtotime($this->hora_inicio)).' a '.
	    	date('H:i',strtotime($this->hora_fin));
	}

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function afterFind()
	{
		parent::afterFind();
		$this->old['dia_semana'] = $this->dia_semana;
	}

	protected function afterSave()
	{
		parent::afterSave();
		if (!$this->isNewRecord)
		{
			$dia = array('Domingo'=>0, 'Lunes'=>1, 'Martes'=>2, 'Miércoles'=>3, 'Jueves'=>4, 'Viernes'=>5, 'Sábado'=>6);
			$formatDia = 'yyyy-MM-dd';
			$delta = $dia[$this->dia_semana] - $dia[$this->old['dia_semana']];
			$delta = sprintf("%+d days",$delta);
			$clases = $this->clases(array('condition'=>'fecha > now()'));
			foreach ($clases as $clase) {
				$timeClase = strtotime($clase->fecha);
				$time = strtotime($delta,$timeClase);
				$clase->fecha = Yii::app()->dateFormatter->format($formatDia,$time);
				$clase->hora_inicio = $this->hora_inicio;
				$clase->hora_fin = $this->hora_fin;
				$clase->save();
			}
		}
	}
}
